<template>
  <div class="file-manager">
    <!-- 顶部工具栏 -->
    <div class="toolbar-container">
      <div class="toolbar">
        <!-- 左侧：搜索和筛选 -->
        <div class="toolbar-left">
          <div class="search-filter-section">
            <div class="search-box">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索文件和文件夹..."
                clearable
                @input="handleSearch"
                class="search-input"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
            
            <el-dropdown trigger="click" class="search-filter-dropdown">
              <el-button size="default" class="filter-btn">
                <el-icon><Filter /></el-icon>
                筛选
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>
                    <div class="filter-section">
                      <div class="filter-title">文件类型</div>
                      <el-checkbox-group v-model="searchFilters.fileTypes" @change="applyFilters">
                        <el-checkbox label="folder">文件夹</el-checkbox>
                        <el-checkbox label="file">文件</el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item divided>
                    <div class="filter-section">
                      <div class="filter-title">共享级别</div>
                      <el-checkbox-group v-model="searchFilters.shareLevels" @change="applyFilters">
                        <el-checkbox label="private">私有</el-checkbox>
                        <el-checkbox label="department">部门</el-checkbox>
                        <el-checkbox label="public">公开</el-checkbox>
                      </el-checkbox-group>
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item divided>
                    <div class="filter-section">
                      <div class="filter-title">时间范围</div>
                      <el-date-picker
                        v-model="searchFilters.dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                        size="small"
                        @change="applyFilters"
                      />
                    </div>
                  </el-dropdown-item>
                  <el-dropdown-item divided>
                    <el-button size="small" @click="clearFilters" style="width: 100%">
                      清除筛选
                    </el-button>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
        
        <!-- 右侧：操作按钮和视图控制 -->
        <div class="toolbar-right">
          <div class="action-buttons">
            <el-button 
              type="primary" 
              @click="showCreateFolderDialog = true"
              class="action-btn"
            >
              <el-icon><FolderAdd /></el-icon>
              新建文件夹
            </el-button>
            
            <el-button 
              type="success" 
              @click="showUploadDialog = true"
              class="action-btn"
            >
              <el-icon><Upload /></el-icon>
              上传文件
            </el-button>
          </div>
          
          <div class="view-controls">
            <el-button-group class="view-toggle">
              <el-button 
                :type="viewMode === 'table' ? 'primary' : ''"
                @click="viewMode = 'table'"
                size="small"
              >
                <el-icon><List /></el-icon>
              </el-button>
              <el-button 
                :type="viewMode === 'grid' ? 'primary' : ''"
                @click="viewMode = 'grid'"
                size="small"
              >
                <el-icon><Grid /></el-icon>
              </el-button>
            </el-button-group>
            
            <el-button @click="refreshFiles" class="refresh-btn">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <div class="breadcrumb-wrapper">
        <el-breadcrumb separator="/" class="breadcrumb">
          <el-breadcrumb-item @click="navigateToFolder(null)" class="breadcrumb-item">
            <el-icon><HomeFilled /></el-icon>
            <span>根目录</span>
          </el-breadcrumb-item>
          <el-breadcrumb-item 
            v-for="folder in breadcrumbPath" 
            :key="folder.id"
            @click="navigateToFolder(folder.id)"
            class="breadcrumb-item"
          >
            {{ folder.name }}
          </el-breadcrumb-item>
        </el-breadcrumb>
        
        <div class="breadcrumb-info">
          <span class="file-count">{{ filteredFiles.length }} 项</span>
          <span v-if="isSearching" class="search-info">
            （从 {{ files.length }} 项中筛选）
          </span>
        </div>
      </div>
    </div>
    
    <!-- 文件列表 - 表格视图 -->
    <div v-if="viewMode === 'table'" class="file-list-container">
      <div class="file-table-wrapper">
        <el-table 
          :data="filteredFiles" 
          v-loading="loading"
          @row-dblclick="handleRowDoubleClick"
          @row-contextmenu="handleRowRightClick"
          class="file-table"
          :header-cell-style="{ background: 'var(--bg-tertiary)', color: 'var(--text-primary)' }"
        >
          <el-table-column label="名称" min-width="300">
            <template #default="{ row }">
              <div class="file-item">
                <div class="file-icon-wrapper">
                  <el-icon class="file-icon" :class="getFileIconClass(row)">
                    <Folder v-if="row.file_type === 'folder'" />
                    <Document v-else />
                  </el-icon>
                </div>
                <div class="file-info">
                  <span class="file-name">{{ row.name }}</span>
                  <span v-if="row.description" class="file-description-inline">{{ row.description }}</span>
                </div>
              </div>
            </template>
          </el-table-column>
          
          <el-table-column label="大小" width="120" align="right">
            <template #default="{ row }">
              <span v-if="row.file_type === 'file'" class="file-size">{{ formatFileSize(row.size) }}</span>
              <span v-else class="file-size-empty">-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="级别" width="80" align="center">
            <template #default="{ row }">
              <el-tag v-if="row.level !== undefined" size="small" class="level-tag">
                L{{ row.level }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="标签" min-width="150">
            <template #default="{ row }">
              <div v-if="row.tags" class="file-tags">
                <el-tag 
                  v-for="tag in getTagList(row.tags)" 
                  :key="tag" 
                  size="small"
                  class="tag-item"
                  effect="light"
                >
                  {{ tag }}
                </el-tag>
              </div>
              <span v-else class="no-tags">-</span>
            </template>
          </el-table-column>
          
          <el-table-column label="共享级别" width="100" align="center">
            <template #default="{ row }">
              <el-tag 
                v-if="row.share_level" 
                :type="getShareLevelTagType(row.share_level)"
                size="small"
                effect="light"
              >
                {{ getShareLevelText(row.share_level) }}
              </el-tag>
            </template>
          </el-table-column>
          
          <el-table-column label="修改时间" width="180">
            <template #default="{ row }">
              <span class="file-date">{{ formatDate(row.updated_at || row.created_at) }}</span>
            </template>
          </el-table-column>
          
          <el-table-column label="操作" width="280" fixed="right" align="center">
            <template #default="{ row }">
              <div class="action-buttons-cell">
                <el-button 
                  type="primary" 
                  size="small" 
                  @click="showRenameFileDialog(row)"
                  class="action-btn-small"
                  link
                >
                  <el-icon><Edit /></el-icon>
                </el-button>
                <el-button 
                  type="info" 
                  size="small" 
                  @click="showEditInfoDialogFunc(row)"
                  class="action-btn-small"
                  link
                >
                  <el-icon><EditPen /></el-icon>
                </el-button>
                <el-button 
                  type="warning" 
                  size="small" 
                  @click="openPermissionDialog(row)"
                  class="action-btn-small"
                  link
                >
                  <el-icon><Lock /></el-icon>
                </el-button>
                <el-button 
                  v-if="row.file_type === 'file'" 
                  type="success" 
                  size="small" 
                  @click="downloadFile(row)"
                  class="action-btn-small"
                  link
                >
                  <el-icon><Download /></el-icon>
                </el-button>
                <el-button 
                  v-if="row.file_type === 'file'" 
                  type="info" 
                  size="small" 
                  @click="openVersionDialog(row)"
                  class="action-btn-small"
                  link
                >
                  <el-icon><Clock /></el-icon>
                </el-button>
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="deleteFile(row)"
                  class="action-btn-small"
                  link
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    
    <!-- 文件列表 - 网格视图 -->
    <div v-else class="file-grid-container">
      <div class="file-grid" v-loading="loading">
        <div 
          v-for="file in filteredFiles" 
          :key="file.id"
          class="file-card"
          @dblclick="handleRowDoubleClick(file)"
          @contextmenu="handleCardRightClick(file, $event)"
        >
          <div class="file-card-header">
            <div class="file-icon-large" :class="getFileIconClass(file)">
              <el-icon>
                <Folder v-if="file.file_type === 'folder'" />
                <Document v-else />
              </el-icon>
            </div>
            <div class="file-card-actions">
              <el-dropdown trigger="click" placement="bottom-end">
                <el-button size="small" circle>
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="showRenameFileDialog(file)">
                      <el-icon><Edit /></el-icon>重命名
                    </el-dropdown-item>
                    <el-dropdown-item @click="showEditInfoDialogFunc(file)">
                      <el-icon><EditPen /></el-icon>编辑信息
                    </el-dropdown-item>
                    <el-dropdown-item @click="openPermissionDialog(file)">
                      <el-icon><Lock /></el-icon>权限设置
                    </el-dropdown-item>
                    <el-dropdown-item v-if="file.file_type === 'file'" @click="downloadFile(file)">
                      <el-icon><Download /></el-icon>下载
                    </el-dropdown-item>
                    <el-dropdown-item v-if="file.file_type === 'file'" @click="openVersionDialog(file)">
                      <el-icon><Clock /></el-icon>版本管理
                    </el-dropdown-item>
                    <el-dropdown-item @click="deleteFile(file)" divided>
                      <el-icon><Delete /></el-icon>删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
          
          <div class="file-card-body">
            <div class="file-name-grid">{{ file.name }}</div>
            <div v-if="file.description" class="file-description-grid">{{ file.description }}</div>
            
            <div class="file-meta">
              <div v-if="file.file_type === 'file'" class="file-size-grid">
                {{ formatFileSize(file.size) }}
              </div>
              <div class="file-date-grid">
                {{ formatDate(file.updated_at || file.created_at) }}
              </div>
            </div>
            
            <div v-if="file.tags" class="file-tags-grid">
              <el-tag 
                v-for="tag in getTagList(file.tags).slice(0, 2)" 
                :key="tag" 
                size="small"
                effect="light"
              >
                {{ tag }}
              </el-tag>
              <span v-if="getTagList(file.tags).length > 2" class="more-tags">
                +{{ getTagList(file.tags).length - 2 }}
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 右键菜单 -->
    <div 
      v-show="contextMenuVisible" 
      class="context-menu"
      :style="{ left: contextMenuPosition.x + 'px', top: contextMenuPosition.y + 'px' }"
      @click.stop
    >
      <div class="context-menu-item" @click="handleContextMenuAction(() => showRenameFileDialog(contextMenuFile))">
        <el-icon><Edit /></el-icon>
        <span>重命名</span>
      </div>
      <div class="context-menu-item" @click="handleContextMenuAction(() => showEditInfoDialogFunc(contextMenuFile))">
        <el-icon><EditPen /></el-icon>
        <span>编辑信息</span>
      </div>
      <div class="context-menu-item" @click="handleContextMenuAction(() => openPermissionDialog(contextMenuFile))">
        <el-icon><Lock /></el-icon>
        <span>权限设置</span>
      </div>
      <div 
        v-if="contextMenuFile?.file_type === 'file'" 
        class="context-menu-item" 
        @click="handleContextMenuAction(() => downloadFile(contextMenuFile))"
      >
        <el-icon><Download /></el-icon>
        <span>下载</span>
      </div>
      <div 
        v-if="contextMenuFile?.file_type === 'file'" 
        class="context-menu-item" 
        @click="handleContextMenuAction(() => openVersionDialog(contextMenuFile))"
      >
        <el-icon><Clock /></el-icon>
        <span>版本管理</span>
      </div>
      <div class="context-menu-divider"></div>
      <div class="context-menu-item danger" @click="handleContextMenuAction(() => deleteFile(contextMenuFile))">
        <el-icon><Delete /></el-icon>
        <span>删除</span>
      </div>
    </div>
    
    <!-- 创建文件夹对话框 -->
    <el-dialog 
      v-model="showCreateFolderDialog" 
      title="新建文件夹" 
      width="500px"
    >
      <el-form :model="folderForm" :rules="folderRules" ref="folderFormRef">
        <el-form-item label="文件夹名称" prop="name">
          <el-input v-model="folderForm.name" placeholder="请输入文件夹名称" />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="folderForm.description" 
            type="textarea" 
            :rows="2"
            placeholder="请输入文件夹描述（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input 
            v-model="folderForm.tags" 
            placeholder="请输入标签，多个标签用逗号分隔（可选）"
            maxlength="200"
          />
          <div class="form-tip">
            多个标签请用逗号分隔，例如：工作,重要,项目
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateFolderDialog = false">取消</el-button>
        <el-button type="primary" @click="createFolder">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 重命名对话框 -->
    <el-dialog 
      v-model="showRenameDialog" 
      title="重命名" 
      width="400px"
    >
      <el-form :model="renameForm" :rules="renameRules" ref="renameFormRef">
        <el-form-item label="新名称" prop="name">
          <el-input v-model="renameForm.name" placeholder="请输入新名称" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showRenameDialog = false">取消</el-button>
        <el-button type="primary" @click="renameFile">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 编辑信息对话框 -->
    <el-dialog 
      v-model="showEditInfoDialog" 
      title="编辑文件信息" 
      width="500px"
    >
      <el-form :model="editInfoForm" :rules="editInfoRules" ref="editInfoFormRef">
        <el-form-item label="文件名称">
          <el-input v-model="currentEditFile.name" disabled />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="editInfoForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入文件描述"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input 
            v-model="editInfoForm.tags" 
            placeholder="请输入标签，多个标签用逗号分隔"
            maxlength="200"
          />
          <div class="form-tip">
            多个标签请用逗号分隔，例如：工作,重要,项目
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showEditInfoDialog = false">取消</el-button>
        <el-button type="primary" @click="updateFileInfo">确定</el-button>
      </template>
    </el-dialog>
    
    <!-- 上传文件对话框 -->
    <el-dialog 
      v-model="showUploadDialog" 
      title="上传文件" 
      width="500px"
    >
      <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef">
        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="uploadComponentRef"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="uploadFileList"
            :limit="1"
            drag
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input 
            v-model="uploadForm.description" 
            type="textarea" 
            :rows="3"
            placeholder="请输入文件描述（可选）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>
        <el-form-item label="标签" prop="tags">
          <el-input 
            v-model="uploadForm.tags" 
            placeholder="请输入标签，多个标签用逗号分隔（可选）"
            maxlength="200"
          />
          <div class="form-tip">
            多个标签请用逗号分隔，例如：工作,重要,项目
          </div>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelUpload">取消</el-button>
        <el-button type="primary" @click="confirmUpload" :loading="uploading">
          {{ uploading ? '上传中...' : '确定上传' }}
        </el-button>
      </template>
    </el-dialog>
    
    <!-- 版本管理对话框 -->
    <el-dialog
      v-model="showVersionDialog"
      title="版本管理"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="version-header">
        <div class="file-info">
          <el-icon><Document /></el-icon>
          <span class="file-name">{{ currentVersionFile?.name }}</span>
        </div>
        <el-button 
          type="primary" 
          size="small" 
          @click="openUploadVersionDialog"
          :disabled="!currentVersionFile"
        >
          <el-icon><Upload /></el-icon>
          上传新版本
        </el-button>
      </div>
      
      <el-table 
        :data="versions" 
        v-loading="versionsLoading"
        style="width: 100%"
        max-height="400px"
      >
        <el-table-column prop="version_number" label="版本号" width="80" />
        <el-table-column prop="size" label="大小" width="100">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column prop="creator_name" label="创建者" width="100" />
        <el-table-column prop="created_at" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDateTime(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column prop="comment" label="备注" min-width="120" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.is_current" type="success" size="small">当前</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="{ row }">
            <el-button 
              type="primary" 
              size="small" 
              @click="downloadVersion(row)"
              link
            >
              下载
            </el-button>
            <el-button 
              v-if="!row.is_current" 
              type="warning" 
              size="small" 
              @click="restoreVersion(row)"
              link
            >
              恢复
            </el-button>
            <el-button 
              v-if="!row.is_current" 
              type="danger" 
              size="small" 
              @click="deleteVersion(row)"
              link
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

    <!-- 上传新版本对话框 -->
    <el-dialog
      v-model="showUploadVersionDialog"
      title="上传新版本"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form 
        ref="uploadVersionFormRef" 
        :model="uploadVersionForm" 
        :rules="uploadVersionRules"
        label-width="80px"
      >
        <el-form-item label="选择文件" prop="file">
          <el-upload
            ref="uploadVersionComponentRef"
            :auto-upload="false"
            :limit="1"
            :on-change="handleVersionFileChange"
            :file-list="uploadVersionFileList"
            :show-file-list="true"
            drag
          >
            <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="版本备注" prop="comment">
          <el-input
            v-model="uploadVersionForm.comment"
            type="textarea"
            :rows="3"
            placeholder="请输入版本备注信息"
            maxlength="200"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="cancelUploadVersion">取消</el-button>
        <el-button type="primary" @click="confirmUploadVersion" :loading="uploadingVersion">
          {{ uploadingVersion ? '上传中...' : '确定上传' }}
        </el-button>
      </template>
    </el-dialog>

    <!-- 权限管理对话框 -->
    <PermissionDialog 
      v-model="showPermissionDialog" 
      :item="currentPermissionItem"
      @saved="refreshFiles"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  FolderAdd, 
  Upload, 
  Refresh, 
  HomeFilled, 
  Folder, 
  Document,
  UploadFilled,
  List,
  Grid,
  Edit,
  EditPen,
  Lock,
  Download,
  Delete,
  MoreFilled,
  Search,
  Filter,
  Clock
} from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import api from '@/utils/api'
import * as versionApi from '@/api/version'
import PermissionDialog from '@/components/PermissionDialog.vue'

const authStore = useAuthStore()

// 响应式数据
const files = ref([])
const loading = ref(false)
const currentFolderId = ref(null)
const breadcrumbPath = ref([])
const viewMode = ref('table') // 'table' 或 'grid'
const showCreateFolderDialog = ref(false)
const showRenameDialog = ref(false)
const currentRenameFile = ref(null)
const showEditInfoDialog = ref(false)
const currentEditFile = ref({})
const showUploadDialog = ref(false)
const uploading = ref(false)
const uploadFileList = ref([])
const showPermissionDialog = ref(false)
const currentPermissionItem = ref(null)

// 版本管理相关数据
const showVersionDialog = ref(false)
const showUploadVersionDialog = ref(false)
const currentVersionFile = ref(null)
const versions = ref([])
const versionsLoading = ref(false)
const uploadingVersion = ref(false)
const uploadVersionFileList = ref([])

// 搜索相关数据
const searchKeyword = ref('')
const searchFilters = reactive({
  fileTypes: ['folder', 'file'], // 默认显示所有类型
  shareLevels: ['private', 'department', 'public'], // 默认显示所有级别
  dateRange: null
})

// 右键菜单相关数据
const contextMenuVisible = ref(false)
const contextMenuPosition = reactive({ x: 0, y: 0 })
const contextMenuFile = ref(null)

// 表单数据
const folderForm = reactive({
  name: '',
  description: '',
  tags: ''
})

const renameForm = reactive({
  name: ''
})

const editInfoForm = reactive({
  description: '',
  tags: ''
})

const uploadForm = reactive({
  file: null,
  description: '',
  tags: ''
})

const uploadVersionForm = reactive({
  file: null,
  comment: ''
})

// 表单验证规则
const folderRules = {
  name: [
    { required: true, message: '请输入文件夹名称', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ],
  tags: [
    { max: 200, message: '标签不能超过200个字符', trigger: 'blur' }
  ]
}

const renameRules = {
  name: [
    { required: true, message: '请输入新名称', trigger: 'blur' }
  ]
}

const editInfoRules = {
  description: [
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ],
  tags: [
    { max: 200, message: '标签不能超过200个字符', trigger: 'blur' }
  ]
}

const uploadRules = {
  file: [
    { required: true, message: '请选择要上传的文件', trigger: 'change' }
  ],
  description: [
    { max: 500, message: '描述不能超过500个字符', trigger: 'blur' }
  ],
  tags: [
    { max: 200, message: '标签不能超过200个字符', trigger: 'blur' }
  ]
}

const uploadVersionRules = {
  file: [
    { required: true, message: '请选择要上传的文件', trigger: 'change' }
  ],
  comment: [
    { max: 200, message: '备注不能超过200个字符', trigger: 'blur' }
  ]
}

// 计算属性
const uploadUrl = computed(() => '/api/files/upload')
const uploadHeaders = computed(() => ({
  Authorization: `Bearer ${authStore.token}`
}))

// 搜索相关计算属性
const isSearching = computed(() => {
  return searchKeyword.value.trim() !== '' || 
         searchFilters.fileTypes.length < 2 ||
         searchFilters.shareLevels.length < 3 ||
         searchFilters.dateRange !== null
})

const filteredFiles = computed(() => {
  let result = [...files.value]
  
  // 关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.toLowerCase().trim()
    result = result.filter(file => {
      return file.name.toLowerCase().includes(keyword) ||
             (file.description && file.description.toLowerCase().includes(keyword)) ||
             (file.tags && file.tags.toLowerCase().includes(keyword))
    })
  }
  
  // 文件类型筛选
  if (searchFilters.fileTypes.length > 0 && searchFilters.fileTypes.length < 2) {
    result = result.filter(file => searchFilters.fileTypes.includes(file.file_type))
  }
  
  // 共享级别筛选
  if (searchFilters.shareLevels.length > 0 && searchFilters.shareLevels.length < 3) {
    result = result.filter(file => {
      const shareLevel = file.share_level || 'private'
      return searchFilters.shareLevels.includes(shareLevel)
    })
  }
  
  // 时间范围筛选
  if (searchFilters.dateRange && searchFilters.dateRange.length === 2) {
    const [startDate, endDate] = searchFilters.dateRange
    result = result.filter(file => {
      const fileDate = new Date(file.updated_at || file.created_at)
      return fileDate >= startDate && fileDate <= endDate
    })
  }
  
  return result
})

// 引用
const folderFormRef = ref()
const renameFormRef = ref()
const editInfoFormRef = ref()
const uploadFormRef = ref()
const uploadComponentRef = ref()
const uploadVersionFormRef = ref()
const uploadVersionComponentRef = ref()

// 方法
const loadFiles = async (parentId = null) => {
  loading.value = true
  try {
    const response = await api.get('/files/', {
      params: { parent_id: parentId }
    })
    files.value = response.data
  } catch (error) {
    ElMessage.error('加载文件列表失败')
  } finally {
    loading.value = false
  }
}

const refreshFiles = () => {
  loadFiles(currentFolderId.value)
}

const navigateToFolder = (folderId) => {
  currentFolderId.value = folderId
  loadFiles(folderId)
  
  // 更新面包屑路径
  if (folderId === null) {
    breadcrumbPath.value = []
  } else {
    // 这里简化处理，实际应该根据文件夹层级构建完整路径
    const folder = files.value.find(f => f.id === folderId)
    if (folder) {
      breadcrumbPath.value = [folder]
    }
  }
}

const handleRowDoubleClick = (row) => {
  if (row.file_type === 'folder') {
    navigateToFolder(row.id)
  }
}

// 右键菜单处理方法
const handleRowRightClick = (row, column, event) => {
  event.preventDefault()
  contextMenuFile.value = row
  contextMenuPosition.x = event.clientX
  contextMenuPosition.y = event.clientY
  contextMenuVisible.value = true
  
  // 添加全局点击事件监听器来隐藏菜单
  const hideContextMenu = () => {
    contextMenuVisible.value = false
    document.removeEventListener('click', hideContextMenu)
  }
  
  // 延迟添加监听器，避免立即触发
  setTimeout(() => {
    document.addEventListener('click', hideContextMenu)
  }, 0)
}

// 网格视图右键菜单处理方法
const handleCardRightClick = (file, event) => {
  event.preventDefault()
  contextMenuFile.value = file
  contextMenuPosition.x = event.clientX
  contextMenuPosition.y = event.clientY
  contextMenuVisible.value = true
  
  // 添加全局点击事件监听器来隐藏菜单
  const hideContextMenu = () => {
    contextMenuVisible.value = false
    document.removeEventListener('click', hideContextMenu)
  }
  
  // 延迟添加监听器，避免立即触发
  setTimeout(() => {
    document.addEventListener('click', hideContextMenu)
  }, 0)
}

// 处理右键菜单项点击
const handleContextMenuAction = (action) => {
  contextMenuVisible.value = false
  action()
}

const createFolder = async () => {
  if (!folderFormRef.value) return
  
  await folderFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await api.post('/files/folder', {
          name: folderForm.name,
          parent_id: currentFolderId.value,
          description: folderForm.description,
          tags: folderForm.tags
        })
        
        ElMessage.success('文件夹创建成功')
        showCreateFolderDialog.value = false
        folderForm.name = ''
        folderForm.description = ''
        folderForm.tags = ''
        refreshFiles()
      } catch (error) {
        ElMessage.error('创建文件夹失败')
      }
    }
  })
}

const showRenameFileDialog = (file) => {
  currentRenameFile.value = file
  renameForm.name = file.name
  showRenameDialog.value = true
}

const renameFile = async () => {
  if (!renameFormRef.value) return
  
  await renameFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const formData = new FormData()
        formData.append('new_name', renameForm.name)
        
        await api.put(`/files/${currentRenameFile.value.id}/rename`, formData)
        
        ElMessage.success('重命名成功')
        showRenameDialog.value = false
        refreshFiles()
      } catch (error) {
        ElMessage.error('重命名失败')
      }
    }
  })
}

const deleteFile = async (file) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除 "${file.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await api.delete(`/files/${file.id}`)
    ElMessage.success('删除成功')
    refreshFiles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

const downloadFile = (file) => {
  window.open(`/api/files/${file.id}/download`, '_blank')
}



const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const formatDateTime = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const openPermissionDialog = (item) => {
  currentPermissionItem.value = item
  showPermissionDialog.value = true
}

// 搜索相关方法
const handleSearch = () => {
  // 搜索逻辑由计算属性 filteredFiles 自动处理
  // 这里可以添加防抖逻辑或其他搜索相关的处理
}

const applyFilters = () => {
  // 筛选逻辑由计算属性 filteredFiles 自动处理
  // 这里可以添加筛选后的额外处理
}

const clearFilters = () => {
  searchKeyword.value = ''
  searchFilters.fileTypes = ['folder', 'file']
  searchFilters.shareLevels = ['private', 'department', 'public']
  searchFilters.dateRange = null
}

const getShareLevelText = (shareLevel) => {
  const map = {
    private: '私有',
    department: '部门',
    public: '公开'
  }
  return map[shareLevel] || shareLevel
}

const getShareLevelTagType = (shareLevel) => {
  const map = {
    private: 'info',
    department: 'warning',
    public: 'success'
  }
  return map[shareLevel] || 'info'
}

const showEditInfoDialogFunc = (file) => {
  currentEditFile.value = file
  editInfoForm.description = file.description || ''
  editInfoForm.tags = file.tags || ''
  showEditInfoDialog.value = true
}

const updateFileInfo = async () => {
  if (!editInfoFormRef.value) return
  
  await editInfoFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await api.put(`/files/${currentEditFile.value.id}/metadata`, {
          description: editInfoForm.description,
          tags: editInfoForm.tags
        })
        
        ElMessage.success('文件信息更新成功')
        showEditInfoDialog.value = false
        refreshFiles()
      } catch (error) {
        ElMessage.error('更新文件信息失败')
      }
    }
  })
}

const getTagList = (tags) => {
  if (!tags) return []
  return tags.split(',').map(tag => tag.trim()).filter(tag => tag)
}

const getFileIconClass = (file) => {
  if (file.file_type === 'folder') {
    return 'folder-icon'
  }
  
  // 根据文件扩展名返回不同的图标类
  const ext = file.name.split('.').pop()?.toLowerCase()
  const imageExts = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp']
  const videoExts = ['mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv']
  const audioExts = ['mp3', 'wav', 'flac', 'aac', 'ogg']
  const docExts = ['doc', 'docx', 'pdf', 'txt', 'rtf']
  const codeExts = ['js', 'ts', 'vue', 'html', 'css', 'py', 'java', 'cpp', 'c']
  
  if (imageExts.includes(ext)) return 'image-icon'
  if (videoExts.includes(ext)) return 'video-icon'
  if (audioExts.includes(ext)) return 'audio-icon'
  if (docExts.includes(ext)) return 'document-icon'
  if (codeExts.includes(ext)) return 'code-icon'
  
  return 'file-icon'
}

const handleFileChange = (file) => {
  uploadForm.file = file.raw
  uploadFileList.value = [file]
}

const cancelUpload = () => {
  showUploadDialog.value = false
  uploadForm.file = null
  uploadForm.description = ''
  uploadForm.tags = ''
  uploadFileList.value = []
  if (uploadComponentRef.value) {
    uploadComponentRef.value.clearFiles()
  }
}

const confirmUpload = async () => {
  if (!uploadFormRef.value) return
  
  await uploadFormRef.value.validate(async (valid) => {
    if (valid && uploadForm.file) {
      uploading.value = true
      try {
        const formData = new FormData()
        formData.append('file', uploadForm.file)
        formData.append('parent_id', currentFolderId.value || '')
        formData.append('description', uploadForm.description)
        formData.append('tags', uploadForm.tags)
        
        await api.post('/files/upload', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        
        ElMessage.success('文件上传成功')
        cancelUpload()
        refreshFiles()
      } catch (error) {
        ElMessage.error('文件上传失败')
      } finally {
        uploading.value = false
      }
    }
  })
}

// 版本管理相关方法
const openVersionDialog = async (file) => {
  currentVersionFile.value = file
  showVersionDialog.value = true
  await loadVersions(file.id)
}

const loadVersions = async (fileId) => {
  versionsLoading.value = true
  try {
    const response = await versionApi.getVersions(fileId)
    versions.value = response.data.versions || []
  } catch (error) {
    ElMessage.error('加载版本列表失败')
    versions.value = []
  } finally {
    versionsLoading.value = false
  }
}

const openUploadVersionDialog = () => {
  showUploadVersionDialog.value = true
  uploadVersionForm.file = null
  uploadVersionForm.comment = ''
  uploadVersionFileList.value = []
}

const handleVersionFileChange = (file) => {
  uploadVersionForm.file = file.raw
}

const cancelUploadVersion = () => {
  showUploadVersionDialog.value = false
  uploadVersionForm.file = null
  uploadVersionForm.comment = ''
  uploadVersionFileList.value = []
  if (uploadVersionComponentRef.value) {
    uploadVersionComponentRef.value.clearFiles()
  }
}

const confirmUploadVersion = async () => {
  if (!uploadVersionFormRef.value) return
  
  await uploadVersionFormRef.value.validate(async (valid) => {
    if (valid && uploadVersionForm.file) {
      uploadingVersion.value = true
      try {
        const formData = new FormData()
        formData.append('file', uploadVersionForm.file)
        formData.append('comment', uploadVersionForm.comment)
        
        await versionApi.createVersion(currentVersionFile.value.id, formData)
        
        ElMessage.success('新版本上传成功')
        cancelUploadVersion()
        await loadVersions(currentVersionFile.value.id)
        refreshFiles()
      } catch (error) {
        ElMessage.error('版本上传失败')
      } finally {
        uploadingVersion.value = false
      }
    }
  })
}

const downloadVersion = async (version) => {
  try {
    const response = await versionApi.downloadVersion(version.file_id, version.version_number)
    const url = window.URL.createObjectURL(new Blob([response.data]))
    const link = document.createElement('a')
    link.href = url
    link.download = `${currentVersionFile.value.name}_v${version.version_number}`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
  } catch (error) {
    ElMessage.error('下载版本失败')
  }
}

const restoreVersion = async (version) => {
  try {
    await ElMessageBox.confirm(
      `确定要恢复到版本 ${version.version_number} 吗？这将创建一个新的当前版本。`,
      '确认恢复',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await versionApi.restoreVersion(version.file_id, version.version_number)
    ElMessage.success('版本恢复成功')
    await loadVersions(currentVersionFile.value.id)
    refreshFiles()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('版本恢复失败')
    }
  }
}

const deleteVersion = async (version) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除版本 ${version.version_number} 吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await versionApi.deleteVersion(version.file_id, version.version_number)
    ElMessage.success('版本删除成功')
    await loadVersions(currentVersionFile.value.id)
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('版本删除失败')
    }
  }
}

// 生命周期
onMounted(() => {
  loadFiles()
})
</script>

<style scoped>
.file-manager {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: var(--bg-primary);
}

/* 工具栏样式 */
.toolbar-container {
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
  padding: 16px 24px;
  backdrop-filter: blur(10px);
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  max-width: 100%;
  gap: 24px;
}

/* 左侧搜索筛选区域 */
.toolbar-left {
  flex: 1;
  max-width: 600px;
}

.search-filter-section {
  display: flex;
  gap: 12px;
  align-items: center;
}

.search-box {
  flex: 1;
  min-width: 300px;
}

.search-input {
  width: 100%;
}

.search-input :deep(.el-input__wrapper) {
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-sm);
  transition: all var(--transition-base);
}

.search-input :deep(.el-input__wrapper:hover) {
  box-shadow: var(--shadow-md);
}

.search-filter-dropdown {
  flex-shrink: 0;
}

.filter-btn {
  height: 40px;
  padding: 0 16px;
  border-radius: var(--border-radius-lg);
  font-weight: 500;
  transition: all var(--transition-base);
  box-shadow: var(--shadow-sm);
  border: 1px solid var(--border-color);
  background: var(--bg-primary);
}

.filter-btn:hover {
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
  border-color: var(--color-primary);
}

/* 右侧操作按钮区域 */
.toolbar-right {
  display: flex;
  align-items: center;
  gap: 16px;
  flex-shrink: 0;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  height: 40px;
  padding: 0 20px;
  border-radius: var(--border-radius-lg);
  font-weight: 500;
  transition: all var(--transition-base);
  box-shadow: var(--shadow-sm);
}

.action-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--shadow-md);
}

.view-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* 筛选下拉菜单样式 */
.filter-section {
  padding: 12px 16px;
  min-width: 200px;
}

.filter-title {
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
  font-size: 14px;
}

.filter-section .el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.filter-section .el-checkbox {
  margin: 0;
}

.filter-section .el-date-picker {
  width: 100%;
}

.view-toggle {
  background: var(--bg-tertiary);
  border-radius: var(--border-radius-md);
  padding: 4px;
}

.view-toggle .el-button {
  border: none;
  background: transparent;
  margin: 0;
  border-radius: var(--border-radius-sm);
}

.view-toggle .el-button.el-button--primary {
  background: var(--color-primary);
  color: white;
}

.refresh-btn {
  height: 36px;
  border-radius: var(--border-radius-md);
  border: 1px solid var(--border-color);
  background: var(--bg-secondary);
  transition: all var(--transition-base);
}

.refresh-btn:hover {
  background: var(--bg-tertiary);
  border-color: var(--color-primary);
}

/* 面包屑样式 */
.breadcrumb-container {
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
  padding: 12px 24px;
}

.breadcrumb-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.breadcrumb {
  flex: 1;
}

.breadcrumb-item {
  cursor: pointer;
  transition: color var(--transition-base);
  display: flex;
  align-items: center;
  gap: 6px;
}

.breadcrumb-item:hover {
  color: var(--color-primary);
}

.breadcrumb-info {
  color: var(--text-secondary);
  font-size: 14px;
}

.file-count {
  background: var(--bg-tertiary);
  padding: 4px 12px;
  border-radius: var(--border-radius-full);
  font-size: 12px;
  font-weight: 500;
}

/* 表格视图样式 */
.file-list-container {
  flex: 1;
  padding: 24px;
  overflow: hidden;
}

.file-table-wrapper {
  height: 100%;
  background: var(--bg-secondary);
  border-radius: var(--border-radius-lg);
  overflow: hidden;
  box-shadow: var(--shadow-sm);
}

.file-table {
  height: 100%;
}

.file-table :deep(.el-table__header) {
  background: var(--bg-tertiary);
}

.file-table :deep(.el-table__row) {
  transition: all var(--transition-base);
}

.file-table :deep(.el-table__row:hover) {
  background: var(--bg-tertiary);
  transform: scale(1.001);
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: var(--border-radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-base);
}

.file-icon {
  font-size: 20px;
  transition: all var(--transition-base);
}

.folder-icon {
  color: var(--color-warning);
}

.image-icon {
  color: var(--color-success);
}

.video-icon {
  color: var(--color-danger);
}

.audio-icon {
  color: var(--color-info);
}

.document-icon {
  color: var(--color-primary);
}

.code-icon {
  color: #8b5cf6;
}

.file-icon {
  color: var(--text-secondary);
}

.file-info {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 2px;
  display: block;
}

.file-description-inline {
  font-size: 12px;
  color: var(--text-secondary);
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-size {
  font-weight: 500;
  color: var(--text-secondary);
}

.file-size-empty {
  color: var(--text-tertiary);
}

.level-tag {
  background: linear-gradient(135deg, var(--color-primary), var(--color-info));
  color: white;
  border: none;
}

.file-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.tag-item {
  margin: 0;
  border-radius: var(--border-radius-sm);
  font-size: 11px;
  padding: 2px 8px;
}

.no-tags {
  color: var(--text-tertiary);
  font-style: italic;
}

.file-date {
  color: var(--text-secondary);
  font-size: 13px;
}

.action-buttons-cell {
  display: flex;
  gap: 8px;
  justify-content: center;
}

.action-btn-small {
  width: 32px;
  height: 32px;
  border-radius: var(--border-radius-md);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all var(--transition-base);
}

.action-btn-small:hover {
  transform: scale(1.1);
  box-shadow: var(--shadow-sm);
}

/* 网格视图样式 */
.file-grid-container {
  flex: 1;
  padding: 24px;
  overflow-y: auto;
}

.file-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  padding: 4px;
}

.file-card {
  background: var(--bg-secondary);
  border-radius: var(--border-radius-lg);
  padding: 20px;
  transition: all var(--transition-base);
  cursor: pointer;
  border: 1px solid var(--border-color);
  position: relative;
  overflow: hidden;
}

.file-card::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, transparent, rgba(255, 255, 255, 0.1));
  opacity: 0;
  transition: opacity var(--transition-base);
}

.file-card:hover {
  transform: translateY(-4px);
  box-shadow: var(--shadow-lg);
  border-color: var(--color-primary);
}

.file-card:hover::before {
  opacity: 1;
}

.file-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
}

.file-icon-large {
  width: 48px;
  height: 48px;
  border-radius: var(--border-radius-lg);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  transition: all var(--transition-base);
}

.file-icon-large.folder-icon {
  background: linear-gradient(135deg, #fbbf24, #f59e0b);
  color: white;
}

.file-icon-large.image-icon {
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
}

.file-icon-large.video-icon {
  background: linear-gradient(135deg, #ef4444, #dc2626);
  color: white;
}

.file-icon-large.audio-icon {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  color: white;
}

.file-icon-large.document-icon {
  background: linear-gradient(135deg, #8b5cf6, #7c3aed);
  color: white;
}

.file-icon-large.code-icon {
  background: linear-gradient(135deg, #6366f1, #4f46e5);
  color: white;
}

.file-icon-large.file-icon {
  background: linear-gradient(135deg, #6b7280, #4b5563);
  color: white;
}

.file-card-actions {
  opacity: 0;
  transition: opacity var(--transition-base);
}

.file-card:hover .file-card-actions {
  opacity: 1;
}

.file-card-body {
  position: relative;
  z-index: 1;
}

.file-name-grid {
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 8px;
  font-size: 14px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-description-grid {
  color: var(--text-secondary);
  font-size: 12px;
  margin-bottom: 12px;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.file-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  font-size: 11px;
  color: var(--text-secondary);
}

.file-size-grid {
  font-weight: 500;
}

.file-date-grid {
  opacity: 0.8;
}

.file-tags-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.file-tags-grid .el-tag {
  font-size: 10px;
  padding: 2px 6px;
  border-radius: var(--border-radius-sm);
}

.more-tags {
  font-size: 10px;
  color: var(--text-secondary);
  background: var(--bg-tertiary);
  padding: 2px 6px;
  border-radius: var(--border-radius-sm);
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: var(--border-radius-lg);
  overflow: hidden;
}

:deep(.el-dialog__header) {
  background: var(--bg-secondary);
  border-bottom: 1px solid var(--border-color);
  padding: 20px 24px;
}

:deep(.el-dialog__body) {
  padding: 24px;
}

:deep(.el-dialog__footer) {
  background: var(--bg-secondary);
  border-top: 1px solid var(--border-color);
  padding: 16px 24px;
}

.form-tip {
  font-size: 12px;
  color: var(--text-secondary);
  margin-top: 6px;
  padding: 8px 12px;
  background: var(--bg-tertiary);
  border-radius: var(--border-radius-sm);
  border-left: 3px solid var(--color-primary);
}

/* 版本管理样式 */
.version-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px;
  background: var(--bg-tertiary);
  border-radius: var(--border-radius-md);
  border: 1px solid var(--border-color);
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-name {
  font-weight: 600;
  color: var(--text-primary);
  font-size: 16px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
  }
  
  .toolbar-left {
    max-width: 100%;
  }
  
  .search-filter-section {
    flex-direction: column;
    gap: 12px;
  }
  
  .search-box {
    min-width: auto;
  }
  
  .toolbar-right {
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 12px;
  }
  
  .action-buttons {
    order: 1;
    flex: 1;
  }
  
  .view-controls {
    order: 2;
    flex-shrink: 0;
  }
  
  .breadcrumb-wrapper {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }
  
  .file-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
  
  .file-list-container,
  .file-grid-container {
    padding: 16px;
  }
  
  .toolbar-container {
    padding: 12px 16px;
  }
  
  .breadcrumb-container {
    padding: 8px 16px;
  }
}

@media (max-width: 480px) {
  .file-grid {
    grid-template-columns: 1fr;
  }
  
  .action-buttons {
    flex-direction: column;
    width: 100%;
  }
  
  .action-btn {
    width: 100%;
    justify-content: center;
  }
}

/* 动画效果 */
.file-card {
  animation: slideUp 0.3s ease-out;
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.file-table :deep(.el-table__row) {
  animation: fadeIn 0.3s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

/* 右键菜单样式 */
.context-menu {
  position: fixed;
  z-index: 9999;
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: var(--border-radius-md);
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.12);
  padding: 8px 0;
  min-width: 160px;
  backdrop-filter: blur(8px);
  animation: contextMenuShow 0.15s ease-out;
}

@keyframes contextMenuShow {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(-8px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.context-menu-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  color: var(--text-primary);
  transition: all 0.2s ease;
  user-select: none;
}

.context-menu-item:hover {
  background: var(--bg-secondary);
  color: var(--color-primary);
}

.context-menu-item.danger {
  color: var(--color-danger);
}

.context-menu-item.danger:hover {
  background: rgba(var(--color-danger-rgb), 0.1);
  color: var(--color-danger);
}

.context-menu-item .el-icon {
  font-size: 16px;
  flex-shrink: 0;
}

.context-menu-divider {
  height: 1px;
  background: var(--border-color);
  margin: 4px 0;
}

/* 右键菜单响应式设计 */
@media (max-width: 768px) {
  .context-menu {
    min-width: 140px;
  }
  
  .context-menu-item {
    padding: 12px 16px;
    font-size: 16px;
  }
  
  .context-menu-item .el-icon {
    font-size: 18px;
  }
}
</style>